<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getDialogTitle"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="category-form"
    >
      <el-form-item v-if="parentCategory" label="父分类">
        <el-input
          :value="`${parentCategory.name} (第${parentCategory.level}级)`"
          disabled
          class="parent-category-input"
        />
      </el-form-item>
      
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入分类名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item v-if="!isEdit && !parentCategory" label="父分类" prop="parentId">
        <el-cascader
          v-model="parentCascaderValue"
          :options="categoryOptions"
          :props="cascaderProps"
          placeholder="请选择父分类（不选则为顶级分类）"
          clearable
          style="width: 100%"
          @change="handleParentChange"
        />
        <div class="form-tip">不选择父分类则创建为顶级分类</div>
      </el-form-item>
      
      <el-form-item label="分类描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="4"
          placeholder="请输入分类描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item v-if="formData.level" label="预计层级">
        <el-tag :type="getLevelTagType(formData.level)" size="large">
          第{{ formData.level }}级分类
        </el-tag>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createCategory, updateCategory, getCategoryList, buildCategoryTree } from '../../../api/category'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  categoryData: {
    type: Object,
    default: null
  },
  parentCategory: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单引用
const formRef = ref()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 是否为编辑模式
const isEdit = computed(() => !!props.categoryData?.id)

// 对话框标题
const getDialogTitle = computed(() => {
  if (props.parentCategory) {
    return `为 "${props.parentCategory.name}" 添加子分类`
  }
  return isEdit.value ? '编辑分类' : '新增分类'
})

// 提交加载状态
const submitLoading = ref(false)

// 分类选项（用于级联选择器）
const categoryOptions = ref([])
const parentCascaderValue = ref([])

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  emitPath: true,
  checkStrictly: true
}

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  parentId: 0,
  description: '',
  level: 1
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '分类描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取层级标签样式
const getLevelTagType = (level) => {
  const typeMap = {
    1: 'danger',   // 第1级 - 红色
    2: 'warning',  // 第2级 - 橙色
    3: 'primary',  // 第3级 - 蓝色
    4: 'success',  // 第4级 - 绿色
    5: 'info'      // 第5级 - 灰色
  }
  return typeMap[level] || 'info'
}

// 获取分类选项（用于父分类选择）
const fetchCategoryOptions = async () => {
  try {
    const response = await getCategoryList()
    if (response.code === 200) {
      categoryOptions.value = buildCategoryTree(response.data)
    }
  } catch (error) {
    console.error('获取分类选项失败:', error)
  }
}

// 处理父分类变化
const handleParentChange = (value) => {
  if (value && value.length > 0) {
    const parentId = value[value.length - 1]
    formData.parentId = parentId
    // 计算层级（父分类层级 + 1）
    const parent = findCategoryById(categoryOptions.value, parentId)
    formData.level = parent ? parent.level + 1 : 1
  } else {
    formData.parentId = 0
    formData.level = 1
  }
}

// 在分类树中查找指定ID的分类
const findCategoryById = (categories, id) => {
  for (const category of categories) {
    if (category.id === id) {
      return category
    }
    if (category.children) {
      const found = findCategoryById(category.children, id)
      if (found) return found
    }
  }
  return null
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    parentId: 0,
    description: '',
    level: 1
  })
  parentCascaderValue.value = []
  formRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
  // 通知父组件清空数据
  emit('update:categoryData', null)
  emit('update:parentCategory', null)
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = {
      name: formData.name,
      parentId: formData.parentId,
      description: formData.description
    }
    
    if (isEdit.value) {
      submitData.id = formData.id
    }
    
    let response
    if (isEdit.value) {
      response = await updateCategory(submitData)
    } else {
      response = await createCategory(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 监听分类数据变化，填充表单
watch(() => props.categoryData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      id: newData.id,
      name: newData.name,
      parentId: newData.parentId,
      description: newData.description || '',
      level: newData.level
    })
  }
}, { immediate: true })

// 监听父分类变化
watch(() => props.parentCategory, (newParent) => {
  if (newParent) {
    formData.parentId = newParent.id
    formData.level = newParent.level + 1
  } else if (!isEdit.value) {
    formData.parentId = 0
    formData.level = 1
  }
}, { immediate: true })

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible) {
    fetchCategoryOptions()
    // 每次打开都先重置表单，避免数据残留
    resetForm()
    // 如果是编辑模式，在下一个tick重新设置数据
    if (props.categoryData) {
      nextTick(() => {
        Object.assign(formData, {
          id: props.categoryData.id,
          name: props.categoryData.name || '',
          parentId: props.categoryData.parentId || 0,
          level: props.categoryData.level || 1,
          description: props.categoryData.description || ''
        })
      })
    }
  }
})

// 页面加载时获取分类选项
onMounted(() => {
  fetchCategoryOptions()
})
</script>

<style scoped>
.category-form {
  padding: 0 20px;
}

.parent-category-input {
  background-color: #f5f7fa;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}
</style>
